from apscheduler.schedulers.asyncio import AsyncIOScheduler
from sqlalchemy.orm import Session
from datetime import datetime
from backend.db.models import Alert
from backend.db.database import get_db
from backend.api.websocket import broadcast_alert  # 后续实现WebSocket广播

# 初始化定时任务调度器
scheduler = AsyncIOScheduler(timezone="UTC")


# 定时任务：检查并发送到期提醒
def check_and_send_alerts(db: Session):
    # 查询当前时间前10分钟内未发送的有效提醒
    now = datetime.utcnow()
    alerts = db.query(Alert).filter(
        Alert.alert_time <= now,
        Alert.is_active == True
    ).all()

    for alert in alerts:
        # 1. 广播提醒给所有在线客户端
        broadcast_alert({
            "alert_id": alert.id,
            "title": alert.title,
            "content": alert.content,
            "alert_time": alert.alert_time.isoformat(),
            "repeat": alert.repeat
        })

        # 2. 处理重复提醒（如每日重复则更新下次提醒时间）
        if alert.repeat == "daily":
            from datetime import timedelta
            alert.alert_time += timedelta(days=1)
        else:
            alert.is_active = False  # 非重复提醒标记为无效

    db.commit()


# 启动调度器（每分钟检查一次）
def start_scheduler():
    db = next(get_db())
    # 添加定时任务（每分钟执行一次）
    scheduler.add_job(
        func=check_and_send_alerts,
        args=[db],
        trigger="interval",
        minutes=1,
        id="alert_check_job",
        replace_existing=True
    )
    scheduler.start()
    print("定时任务调度器已启动")